package com.lxr0860.lxr0860production_test.itemactivity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;


import com.lxr0860.lxr0860production_test.R;
import com.lxr0860.lxr0860production_test.utils.AudioRecorderUtils;
import com.lxr0860.lxr0860production_test.utils.Contants;
import com.lxr0860.lxr0860production_test.view.CircleProgress;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;

public class MicActivity extends Activity {
    private Button mBtnStart;
    private ImageButton mIbPlay;
    private TextView mTvTips;
    private TextView mTvTime;
    private AudioRecorderUtils mAudioUtils;
    private CircleProgress mProgress;
    private boolean isPlaying;
    private boolean stateMusic;
    private MediaPlayer mMediaPlayer;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Contants.DIALOG_POSITIVE:
                    Intent mIntent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("result", true);
                    mIntent.putExtras(bundle);
                    MicActivity.this.setResult(Contants.TEST_ITEM_MIC, mIntent);
                    finish();
                    break;
                case Contants.DIALOG_NEGATIVE:
                    finish();
                    break;
            }
        }
    };
    private long mMusicTime;

    private Runnable musicRunnable = new Runnable() {
        @Override
        public void run() {
            mProgress.setProgress((int) mMusicTime/100);
//            mProgress.setTextSize((int) (mMusicTime*10));
            mTvTime.setText(formatTime(mMusicTime));
            mMusicTime -= mAudioUtils.SPACE;
            handler.postDelayed(this, mAudioUtils.SPACE);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_sound);
        initView();
        initData();
        initEvent();
    }

    private void initView() {
        mBtnStart = (Button) findViewById(R.id.btnSound);
        mIbPlay = (ImageButton) findViewById(R.id.ib_audio_play);
        mTvTips = (TextView) findViewById(R.id.tv_audio_tip);
        mTvTime = (TextView) findViewById(R.id.tv_audio_time);
        mProgress = findViewById(R.id.pb_audio_progress);
    }

    private void initData() {
//        mProgress.setMax(AudioRecorderUtils.MAX_LENGTH);
        mAudioUtils = new AudioRecorderUtils();
        mProgress.setProgressColor(mProgress.progressColor);
        mProgress.setPreProgressColor(mProgress.preColor);
        mAudioUtils.setOnAudioStatusUpdateListener(new AudioRecorderUtils.OnAudioStatusUpdateListener() {
            @Override
            public void onUpdate(double db, long time) {
                mProgress.setProgress((int) time/100);
                mTvTime.setText(formatTime(time));
            }

            @Override
            public void onStop(String filePath) {
                Log.e("cly", "onStop-->" + filePath);
                mAudioUtils.stopRecord();
                isPlaying = false;
                mIbPlay.setBackgroundResource(R.drawable.stop);
                scanAudio(filePath);
                mTvTips.setText("录音已完成，请听声音是否正常");
                prepareMusic(filePath);
                stateMusic = true;
                mIbPlay.performClick();
            }
        });
    }

    private void initEvent() {
        mBtnStart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mBtnStart.setEnabled(false);
                stateMusic = false;
                mTvTips.setText("请勿遮挡麦克风，一秒后开始录音");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mIbPlay.setVisibility(View.VISIBLE);
                        mIbPlay.setBackgroundResource(R.drawable.stop);
                        mTvTips.setText("正在进行录音测试");
                        mProgress.setProgress(0);
                        mAudioUtils.startRecord();
                        isPlaying = true;
                    }
                }, 1000);
            }
        });
        mIbPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isPlaying) {
                    mIbPlay.setBackgroundResource(R.drawable.start);
                    if (stateMusic) {
                        pauseMusic();
                    } else {
                        mTvTime.setText("录音已暂停");
                        mAudioUtils.pauseRecoder();
                    }
                } else {
                    mIbPlay.setBackgroundResource(R.drawable.stop);
                    if (stateMusic) {
                        startMusic();
                    } else {
                        mTvTime.setText("录音已开始");
                        mAudioUtils.resumeRecoder();
                    }
                }
                isPlaying = !isPlaying;
            }
        });
    }

    private void prepareMusic(final String filePath) {
        mMusicTime = AudioRecorderUtils.MAX_LENGTH;
        AudioManager audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, 30, AudioManager.FLAG_SHOW_UI);
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
        }
        try {
            mMediaPlayer.reset();
            mMediaPlayer.setDataSource(filePath);
            mMediaPlayer.prepare();
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mp.stop();
                    isPlaying = false;
                    mIbPlay.setBackgroundResource(R.drawable.stop);
                    handler.removeCallbacks(musicRunnable);
                    mProgress.setProgress(0);
                    mTvTime.setText("播放完毕");
                    mTvTips.setText("测试完毕");
                    mBtnStart.setEnabled(true);
                    prepareMusic(filePath);
                    Contants.showDailog(MicActivity.this, "MIC测试完毕，是否保存结果", handler, Gravity.TOP);
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void startMusic() {
        mTvTips.setText("正在进行音乐测试");
        mTvTime.setText("播放已开始");
        if (!mMediaPlayer.isPlaying()) {
            handler.post(musicRunnable);
            mMediaPlayer.start();
        }
    }

    private void pauseMusic() {
        mTvTime.setText("播放已暂停");
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            handler.removeCallbacks(musicRunnable);
        }
    }

    private void realseMusic() {
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAudioUtils.cancelRecord();
        realseMusic();
    }

    private void scanAudio(String path) {
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                Uri.fromFile(new File(path))));
    }

    private String formatTime(long time) {
        SimpleDateFormat formatter = new SimpleDateFormat("mm:ss");
        String formatTime = formatter.format(time);
        return formatTime;
    }
}